﻿using System;
using System.Web.Mvc;
using SuperiorCommon;
using SuperiorModel;
using SuperiorShopBussinessService;
using Redis;
using WxPayAPIMobileShopCode.Common.Helpers;
using ThoughtWorks.QRCode.Codec;
using System.Drawing;
using System.Text;
using System.IO;
using System.Drawing.Imaging;

namespace SuperiorShopkeeper.Controllers
{
    [JsonException]
    [CheckLoginFitler]
    public class HomeController : BaseController
    {
        private readonly IHomeService _IHomeService;
        private readonly IShopService _IShopService;

        public HomeController(IHomeService IHomeService, IShopService IShopService)
        {
            _IHomeService = IHomeService;
            _IShopService = IShopService;
        }
        protected override void Dispose(bool disposin)
        {
            this._IHomeService.Dispose();
            this._IShopService.Dispose();   
            base.Dispose(disposin);
        }

        // GET: Home
        public ActionResult Index()
        {

            return View();
        }

        public ActionResult _Index()
        {
            var model = _IHomeService.GetHomeData(UserContext.DeSecretId.ToInt());
            return View(model);
        }
        /// <summary>
        /// 获取近7日每日用户增长量报表数据
        /// </summary>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult GetAddUserChart()
        {
            var model = _IHomeService.GetAddUserChart(UserContext.DeSecretId.ToInt());
            return Success(model);
        }

        /// <summary>
        /// 获用户类型分布的报表数据
        /// </summary>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult GetTypeUserChart()
        {
            var model = _IHomeService.GetTypeUserChart(UserContext.DeSecretId.ToInt());
            return Success(model);
        }
        /// <summary>
        /// 获取近7日每日销售额和销售量报表数据
        /// </summary>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult GetSallChart()
        {
            var model = _IHomeService.GetSallChart(UserContext.DeSecretId.ToInt());
            return Success(model);
        }
        /// <summary>
        /// 充值页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Recharge()
        {
            var model = _IShopService.GetRechargeList();
            return View(model);
        }
        /// <summary>
        /// 提交充值
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        
        public ActionResult CommitRecharge(int id)
        {
            
            return View();
        }

        public ActionResult CreateRechareQr(int id)
        {
            int shopAdminId = UserContext.DeSecretId.ToInt();
            string msg = "";
            var createModel = _IHomeService.CreateRechargeOrder(shopAdminId, id, out msg);
            if (!string.IsNullOrEmpty(msg))
            {
                LogManger.Instance.WriteLog("商户"+UserContext.DeSecretId+"生成支付订单出错："+msg);
                return Error(msg);
            }
            Session["CURRENT_ORDERID"] = createModel.Id;
            string url = WeiXinCreateOrder(createModel);
            //初始化二维码生成工具
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            qrCodeEncoder.QRCodeVersion = 0;
            qrCodeEncoder.QRCodeScale = 4;

            //将字符串生成二维码图片
            Bitmap image = qrCodeEncoder.Encode(url, Encoding.Default);

            //保存为PNG到内存流 
            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);
            return new FileContentResult(ms.GetBuffer(), @"image/png");
        }



        private string WeiXinCreateOrder(CreateRechargeOrderResult model)
        {
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            string notifyurl = ConfigSettings.Instance.WxRechargeNoticeUrl;
          
            string paykey = ConfigSettings.Instance.PaySecret;
            string time_start = DateTime.Now.ToString("yyyyMMddHHmmss");
            string time_expire = DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss");
            //统一下单
            WxPayData data = new WxPayData();
            data.SetValue("appid", ConfigSettings.Instance.APPID);//公众账号ID
            data.SetValue("mch_id", ConfigSettings.Instance.Merchant_Id);//商户号
            data.SetValue("nonce_str", ToolManager.GenerateNonceStr());//随机字符串
            data.SetValue("body", "优越店长充值");//商品描述
            data.SetValue("attach", UserContext.User.Id);//附加数据
            data.SetValue("out_trade_no", model.OrderNo);//商户订单号
            data.SetValue("total_fee", (int)Math.Round(model.Amount * 100));//总金额 单位分
            data.SetValue("time_start", time_start);
            data.SetValue("time_expire", time_expire);
            //data.SetValue("goods_tag", "test");//商品标记 代金券或立减优惠功能的参数
            data.SetValue("trade_type", "NATIVE");
            data.SetValue("product_id", model.Id);//商品ID
            //data.SetValue("openid", model.Openid);
            data.SetValue("notify_url", notifyurl);//异步通知url
            data.SetValue("spbill_create_ip", "");//终端ip
            data.SetValue("sign", data.MakeSign(ConfigSettings.Instance.PaySecret));
            string xml = data.ToXml();
            string response = WeiXinHelper.Post(xml, url, false, 10);

            LogManger.Instance.WriteLog("微信统一下单" + response);
            WxPayData result = new WxPayData();
            result.FromXml(response);
            string res = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
            return res;
        }
        /// <summary>
        /// 充值微信回调
        /// </summary>
        /// <param name="orderno"></param>
        /// <param name="paycode"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult WxRechargeCallBack(string orderno, string paycode, int state)
        {
            
           
            return Success(true);
        }
        /// <summary>
        /// 检测小程序版本是否有更新
        /// </summary>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult CheckVersion(int isnotice = 0)
        {
            var version = CookieHelper.GetCookieValue("YYDZ_PROGRAM_VERSION");
            var lasterVersion = RedisManager.GetLasterItemFromList<VersionItem>("Version");
            if (lasterVersion != null)
            {
                if (lasterVersion.Version != version)
                {
                    //if (isnotice == 1)//用户点了知道了
                    //{
                    //    CookieHelper.SetCookie("YYDZ_PROGRAM_VERSION", lasterVersion.Version, DateTime.Now.AddYears(20));
                    //}
                    
                    return Success(lasterVersion.Msg);
                }
            }
            return Success("");
            
        }
        /// <summary>
        /// 推送消息，用户点我知道了，记录当前版本得信息cookie
        /// </summary>
        /// <returns></returns>
        [AjaxOnly]
        public JsonResult SetNoticeCookie()
        {
            var lasterVersion = RedisManager.GetLasterItemFromList<VersionItem>("Version");
            CookieHelper.SetCookie("YYDZ_PROGRAM_VERSION", lasterVersion.Version, DateTime.Now.AddYears(20));
            return Success(true);
        }
        /// <summary>
        /// 操作文档
        /// </summary>
        /// <returns></returns>
        public ActionResult OptionWord()
        {
            return View();
        }
        /// <summary>
        /// 常见问题
        /// </summary>
        /// <returns></returns>
        public ActionResult Questions()
        {
            return View();
        }
    }
}